﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleRobot_2
{
    public class GameRules
    {
        public int fieldHeight;
        public int fieldWidth;
        public List<Robot> playingRobots;
        private int _targetX;
        private int _targetY;

        private Random _random = new Random();

        private void PlaceTarget()
        {
            int x = 0;
            int y = 0;
            do
            {
                x = _random.Next(0, this.fieldWidth - 1);
                y = _random.Next(0, this.fieldHeight - 1);
            }
            while (IsPositionFree(x, y));
            _targetX = x;
            _targetY = y;
        }
        private Robot IsWinnerFound()
        {
            foreach (Robot r in this.playingRobots)
            {
                if (r._x == this._targetX && r._y == this._targetY)
                    return r;
            }
            return null;
        }

        public bool IsPositionFree(int x, int y)
        {
            return true;
        }
        public void StartGame(int fh, int fw, IEnumerable<Robot> robots)
        {
            this.fieldHeight = fh;
            this.fieldWidth = fw;
            foreach (Robot r in robots)
            {
                InitRobotPosition(r);
            }
            while (IsWinnerFound() == null)
            {
                foreach (Robot r in this.playingRobots)
                {
                    int currentRobotX = r._x;
                    int currentRobotY = r._y;
                    try
                    {
                        r.DoStep();
                        if (Math.Abs(r._x - currentRobotX) > 1  ||  Math.Abs(r._y - currentRobotY)>1)
                        {
                            r.SetPosition(currentRobotX, currentRobotY);
                        }
                    }
                    catch
                    {
                        r.SetPosition(currentRobotX, currentRobotY);
                    }
                    r.Print();
                }
            }               
            Thread.Sleep(500);
        }
        private void InitRobotPosition(Robot r)
        {
            int x = 0;
            int y = 0;
            do
            {
                x = _random.Next(0, this.fieldWidth - 1);
                y = _random.Next(0, this.fieldHeight - 1);

            }
            while (IsPositionFree(x, y));
            r.SetPosition(x, y);
            this.playingRobots.Add(r);
        }
        
    }
}
